package com.yupi.referral.service;

import com.yupi.referral.config.MinioConfig;
import com.yupi.referral.utils.FileUploadUtils;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@Service
public class FileService {
    @Autowired
    MinioConfig config;
    @Autowired
    MinioClient minioClient;

    public String uploadFile(MultipartFile file) throws IOException, ServerException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        //随机生成文件名
        String filename = FileUploadUtils.extractFileName(file);
        InputStream is = file.getInputStream();
        PutObjectArgs args = PutObjectArgs.builder()
                .bucket(config.getBucketName())
                .object(filename)
                .stream(is, file.getSize(), -1)
                .contentType(file.getContentType())
                .build();
        minioClient.putObject(args);
        StringBuilder finalFileName =
                new StringBuilder(config.getUrl());
        finalFileName
                .append("/")
                .append(config.getBucketName())
                .append("/")
                .append(filename);

        return finalFileName.toString();
    }
}
